package com.lovecaa.order;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 生产者-发送顺序消息
 * 创建时间： 2023年10月22日 17:00:00
 *
 * @author Mr.Tao
 * @since 1.0.0
 */
public class OrderProducer {
    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        DefaultMQProducer producer = new DefaultMQProducer("AsyncProducerGroup");
        producer.setNamesrvAddr("192.168.192.110:9876");
        producer.start();
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 10; j++) {
                String topic = "OrderTest";
                String tag = "TagA";
                byte[] msg = ("AsyncProducer_" + i + "_" + j).getBytes(StandardCharsets.UTF_8);
                Message message = new Message(topic, tag, msg);
                SendResult sendResult = producer.send(message, new MessageQueueSelector() {
                    /**
                     * 选择一个queue来发送消息
                     * @param list 所有queue的list
                     * @param msg 要发送的消息
                     * @param arg 用于取模的参数
                     * @return 发送消息的queue
                     */
                    @Override
                    public MessageQueue select(List<MessageQueue> list, Message msg, Object arg) {
                        // 这个arg就是外层的i，用外层的i对所有的queue进行取模，让同一个循环的消息发送到同一个queue
                        Integer id = (Integer) arg;
                        int index = id % list.size();
                        return list.get(index);
                    }
                }, i);
                System.out.println("消息发送成功:" + sendResult);
            }
        }
    }
}
